#-------------------------------------------------------------------------------
# Name:        pyp2pserver
# Purpose:     pyrex模块，模仿p2pserver，加载dll扩展，提供在python中调试dll扩展的功能
#
# Author:      seewind
#
# Created:     28-02-2008
# Copyright:   (c) seewind 2008
# Licence:     <your licence>
#-------------------------------------------------------------------------------

cdef extern from "windows.h":
    ctypedef int (__cdecl *FARPROC)()
    void * LoadLibraryA(char *lpLibFileName)
    FARPROC GetProcAddress(void *dllhandle, char *funcname)

cdef extern from "python.h":
    object PyString_FromStringAndSize(char *s, Py_ssize_t size)
    int PyString_AsStringAndSize(object obj, char **s, Py_ssize_t *size)

cdef extern from "p2pserverif.h":
    struct p2pserver_interface:
        void (*senddatafunc) (char *peerid, char *data, int size)

cdef extern from "p2pserverexif.h":
    struct p2pserver_exinterface:
        void (__cdecl *peer_state_changefunc)(char *peerid, int peer_state)
        void (__cdecl *receive_datafunc) (char *peerid, char *data, int size)
        
    ctypedef p2pserver_exinterface(__cdecl *INITEXIFFUNC) (p2pserver_interface stp2pserver)
    ctypedef void (__cdecl *UNINITEXIFPROC) (p2pserver_exinterface stp2pserverex)



#
cdef public struct st1:
    int ver
#cdef api void api_func(void *p1):
#    pass
    
cdef void senddata(char *peerid, char *data, int size):
    global globalp2pserver
    if globalp2pserver:
        globalp2pserver.senddata(peerid, PyString_FromStringAndSize(data, size))
    
cdef class P2pserver:
    cdef void  *_lib
    cdef INITEXIFFUNC initexif
    cdef p2pserver_interface p2pserver_if
    cdef p2pserver_exinterface p2p_exif
    
    def __cinit__(self):
        #global globalp2pserver
        #globalp2pserver = self
        pass
        
    def load(self):
        if not self._lib:
            self.p2pserver_if.senddatafunc = senddata
            
            self._lib = LoadLibraryA("storeserver.dll")
            self.initexif = <INITEXIFFUNC>GetProcAddress(self._lib, "initexif") 
            self.p2p_exif = self.initexif(self.p2pserver_if)
        
        return None
    
    def senddata(self, peerid, data):
        print 'senddata', peerid, data
       
    def peer_state_change(self, peerid, peer_state):
        self.p2p_exif.peer_state_changefunc(peerid, peer_state)
    
    def receive_data(self, peerid, data):
        cdef char *cdata
        cdef Py_ssize_t size,
        
        if PyString_AsStringAndSize(data, &cdata, &size) == 0:
            self.p2p_exif.receive_datafunc(peerid, cdata, size)
        
            
globalp2pserver = P2pserver()
